<?php

namespace App\Console\Commands\ChatGroup;

use App\Library\FeiShu\SendFs;
use App\Models\ChatGroup\ChatGroupDataStatisticsModel;
use App\Models\ChatGroup\ChatGroupHistoryModel;
use App\Models\ChatGroup\ChatGroupSessionAppraiseModel;
use App\Models\ChatGroup\ChatGroupSessionModel;
use Illuminate\Console\Command;
use Kuafu\GeneralFs\BuildFs;

class DataStatistics extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'chatGroup:dataStatistics {start?} {end?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每天会话数据统计';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {

        $startTime = $this->argument('start');
        if (!$startTime) {
            $startTime = date('Y-m-d', strtotime('-1 day'));//昨天时间
        }
        $endTime = $this->argument('end');
        if (!$endTime) {
            $endTime = date('Y-m-d 23:59:59', strtotime('-1 day'));
        } else {
            $endTime = $endTime . ' 23:59:59';
        }

        // 当日会话数
        $groupSessionCount = ChatGroupSessionModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->count();

        // 当日会话门店数
        $groupSessionShopCount = ChatGroupSessionModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->groupBy('shopId')
            ->select('shopId')
            ->get()
            ->count();

        // 吐出答案的会话数
        $groupSessionAnswerCount = ChatGroupHistoryModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('isAnswer', ChatGroupHistoryModel::GET_ANSWER)// 存在答案
            ->groupBy('sessionId')
            ->select('sessionId')
            ->get()
            ->count();

        // 当日会话吐答案的比率 = 吐出答案的会话数/当日会话数
        $groupSessionAnswerRate = $groupSessionAnswerCount && $groupSessionCount ? round($groupSessionAnswerCount * 100 / $groupSessionCount, 2) . '%' : 0;

        // 发起呼叫人工次数
        $callCustomerCount = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_CALL)// 发起呼叫
            ->count();

        // 发起呼叫人工的门店数
        $callCustomerShopCount = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_CALL)// 发起呼叫
            ->groupBy('shopId')
            ->select('shopId')
            ->get()
            ->count();

        // 呼叫会话的客服介入数
        $callCustomerJoinCount = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_CALL_CUSTOMER)// 人工客服
            ->groupBy('sessionId')
            ->select('sessionId')
            ->get()
            ->count();

        // 呼叫人工应答率 = 呼叫会话的客服介入数/发起呼叫人工的次数
        $callCustomerRate = $callCustomerJoinCount && $callCustomerCount ? round($callCustomerJoinCount * 100 / $callCustomerCount, 2) . '%' : 0;

        // 人工响应时长:平均数
        $callCustomerAverage = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_CALL_TIME)// 响应时长 单位s
            ->average('statisticData');

        // 人工响应时长:最大值
        $callCustomerMax = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_CALL_TIME)// 响应时长 单位s
            ->max('statisticData');

        // 人工响应时长:最小值
        $callCustomerMin = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_CALL_TIME)// 响应时长 单位s
            ->min('statisticData');

        // 评价卡统计-已解决数
        $appraiseResolvedCount = ChatGroupSessionAppraiseModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('solve', ChatGroupSessionAppraiseModel::SOLVE_YES)
            ->count();

        // 评价卡统计-未解决数
        $appraiseUnresolvedCount = ChatGroupSessionAppraiseModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('solve', ChatGroupSessionAppraiseModel::SOLVE_NO)
            ->count();

        // 评价卡统计-未填写数
        $appraiseNotFillInCount = ChatGroupSessionAppraiseModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('solve', 0)
            ->count();

        // 评价卡满意度-满分数
        $appraiseFullScoreCount = ChatGroupSessionAppraiseModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('score', 5)
            ->count();

        // 评价卡满意度-非满分数
        $appraiseNotFullCount = ChatGroupSessionAppraiseModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->whereBetween('score', [1, 4])
            ->count();

        // 评价卡满意度-未填写数
        $appraiseNotScoreCount = ChatGroupSessionAppraiseModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('score', 0)
            ->count();

        // 答案卡露出总次数(去重)
        $answerCardCount = ChatGroupHistoryModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupHistoryModel::TYPE_DIALOG)
            ->whereRaw(
                "JSON_VALID( content )
	AND JSON_EXTRACT( content, '$.btn' ) IS NOT NULL
	AND JSON_EXTRACT( content, '$.btn' ) != ''
	AND JSON_EXTRACT( content, '$.isAiAnswer' ) = false "
            )
            ->count();

        // 总点赞数
        $useFullTotal = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_FAQ_ANSWER_USE_FULL)
            ->count();

        // 总踩数
        $useLessCount = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_FAQ_ANSWER_USE_LESS)
            ->count();

        // AI吐答案总次数(去重)
        $answerCardAICount = ChatGroupHistoryModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupHistoryModel::TYPE_DIALOG)
            ->whereRaw(
                " JSON_VALID( content )
	AND JSON_EXTRACT( content, '$.btn' ) IS NOT NULL
	AND JSON_EXTRACT( content, '$.btn' ) != ''
	AND JSON_EXTRACT( content, '$.isAiAnswer' ) = true "
            )
            ->count();


        // AI总赞数
        $useFullAiTotal = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_FAQ_ANSWER_USE_FULL_AI)
            ->count();

        // Al总踩数
        $useLessAiCount = ChatGroupDataStatisticsModel::query()
            ->whereBetween('createdAt', [strtotime($startTime), strtotime($endTime)])
            ->where('type', ChatGroupDataStatisticsModel::TYPE_FAQ_ANSWER_USE_LESS_AI)
            ->count();

        $templateData = [
            'startTime'               => $startTime,
            'groupSessionCount'       => $groupSessionCount,
            'groupSessionShopCount'   => $groupSessionShopCount,
            'groupSessionAnswerRate'  => $groupSessionAnswerRate,
            'callCustomerCount'       => $callCustomerCount,
            'callCustomerShopCount'   => $callCustomerShopCount,
            'callCustomerRate'        => $callCustomerRate,
            'callCustomerAverage'     => round($callCustomerAverage, 2),
            'callCustomerMax'         => $callCustomerMax ?? 0,
            'callCustomerMin'         => $callCustomerMin ?? 0,
            'appraiseResolvedCount'   => $appraiseResolvedCount,
            'appraiseUnresolvedCount' => $appraiseUnresolvedCount,
            'appraiseNotFillInCount'  => $appraiseNotFillInCount,
            'appraiseFullScoreCount'  => $appraiseFullScoreCount,
            'appraiseNotFullCount'    => $appraiseNotFullCount,
            'appraiseNotScoreCount'   => $appraiseNotScoreCount,
            'answerCardCount'         => $answerCardCount,
            'useFullTotal'            => $useFullTotal,
            'useLessCount'            => $useLessCount,
            'answerCardAICount'       => $answerCardAICount,
            'useFullAiTotal'          => $useFullAiTotal,
            'useLessAiCount'          => $useLessAiCount,
        ];

        $templateJson = view()->file(app_path('Remote/Feishu/FsTemplate/ChatGroup/ChatGroupDataStatisticsFsTemplate.blade.php'), $templateData)->render();

        // 飞书机器人推送
        BuildFs::newRobot(SendFs::ROBOT_AI_CHAT_DATA_STATISTICS, BuildFs::MSG_TYPE_CARD)
            ->setCardContent(json_decode($templateJson, true))
            ->send();

    }
}

